package com.rp.system.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rp.common.aspect.annotetion.AutoLog;
import com.rp.common.aspect.annotetion.ResponseResultBody;
import com.rp.common.config.redis.RedisUtil;
import com.rp.common.result.ResultDTO;
import com.rp.system.user.entity.SysRolePermission;
import com.rp.system.user.model.SysRolePermissionModel;
import com.rp.system.user.service.SysRolePermissionService;
import com.rp.common.utils.Selectway;
import com.rp.system.user.service.impl.SysPermissionServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限表 前端控制器
 * </p>
 *
 * @author vicente
 * @since 2020-12-01
 */
@Api(tags = "角色权限表")
@RestController
@RequestMapping("/sys-role-permission")
@Slf4j
@ResponseResultBody
public class SysRolePermissionController {

    @Autowired
    private SysRolePermissionService sysRolePermissionService;

    @Autowired
    private Selectway selectway;

    @Autowired
    private RedisUtil redisUtil;

    @RequiresPermissions("sysRole:authorization")
    @GetMapping("/list")
    @AutoLog(value = "角色权限表-角色拥有的所有权限列表")
    @ApiOperation(value = "角色拥有的所有权限列表")
    public ResultDTO<List<String>> list(
            @RequestParam @ApiParam(value = "角色id", required = true) String role_id
    ) {
        List<SysRolePermission> list = sysRolePermissionService.list(new QueryWrapper<SysRolePermission>().select("permission_id").eq("role_id", role_id));
        return ResultDTO.success().data(list.stream().map(SysRolePermission::getPermissionId).collect(Collectors.toList()));
    }


    @RequiresPermissions("sysRole:authorization")
    @PostMapping("/update")
    @AutoLog(value = "角色权限表-给角色分配权限")
    @ApiOperation(value = "给角色分配权限")
    public ResultDTO<Boolean> insert(@RequestBody SysRolePermissionModel sysRolePermissionModel) {
        redisUtil.delAll(SysPermissionServiceImpl.KEY_STRING);
        redisUtil.del("system:user:*");
        return ResultDTO.tf(sysRolePermissionService.insertOrDelete(sysRolePermissionModel));
    }

}
